import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from './index'
import PrevLoading from '@/components/PrevLoading/server'

// 页面加载动画白名单路由（不显示动画的页面路由name）
const loadingWhiteList = ['Main', 'Login', '404']
const whiteList = ['/test/test-audio', '/test/batch-upload']

// 每个路由都进行拦截
router.beforeEach(async (to, from, next) => {
  // 页面加载动画
  if (!loadingWhiteList.includes(to.name)) {
    PrevLoading.open()
    NProgress.configure({showSpinner: false})
    NProgress.start()
  }
  // 白名单（测试用）
  if (whiteList.includes(to.path) || to.path.includes('/test', 0)) {
    next()
  } else if (to.name === 'Login') {
    // 登录页面
    next()
  } else if (to.query.id && to.query.JSESSIONID) {
    if (!store.getters.settingsLoading) {
      // 加载基础配置
      await store.dispatch('auth/setUserId', to.query.id)
      await store.dispatch('settings/getSettings', to.query.id)
    }
    next()
  } else {
    if (from.query.id && from.query.JSESSIONID) {
      next({
        // ...to,
        path: to.path,
        replace: !!to.query.replace,
        query: {
          id: from.query.id, // 登录用户 id
          JSESSIONID: from.query.JSESSIONID, // 登录用户 JSESSIONID
          // 参数
          ...to.query,
          // 路由跳转的时候，是相同的路由是不会跳转，页面也不会有更新的
          random: +new Date().getTime(),
          _t: +new Date().getTime()
        }
      })
    } else {
      next({
        name: 'Login',
        query: {
          random: new Date().getTime()
        }
      })
    }
  }
})

// 路由加载后
router.afterEach((to, from) => {
  PrevLoading.close()
  NProgress.done()
})
